//
//  LCSearchVC.m
//  LongChain
//
//  Created by FengZi on 2018/4/7.
//  Copyright © 2018年 FengZi. All rights reserved.
//

#import "LCSearchVC.h"
#import "LCSearchResultVC.h"
#import "LCSearchCell.h"
#import "LCFileTypeCell.h"
#import "LCFileCell.h"
#import "LCSearchHistoriesFooter.h"
#import "LCFileModel.h"

@interface LCSearchVC ()<UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating,UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UINavigationControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
// 数据源数组
@property (nonatomic, strong) NSMutableArray *datas;

@property (nonatomic, assign) CGFloat headHeight;

@property (weak, nonatomic) IBOutlet UICollectionView *collection;

@property (nonatomic, strong) UISearchController *searchController;

@property (nonatomic, strong) NSMutableArray *historys;

@property (nonatomic, strong) NSMutableArray *results;

@property (nonatomic, strong) UIView *customNavigation;

@property (nonatomic, strong) NSArray *fileType;


@property (weak, nonatomic) IBOutlet UILabel *noDatasDes;

@property (weak, nonatomic) IBOutlet UIView *noDatasBaseView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *actionBaseViewHeight;

@property (weak, nonatomic) IBOutlet UIView *actionBaseView;

@property (nonatomic, copy) NSString *searchKey;

@property (nonatomic, assign) NSInteger searchPage;

@property (nonatomic, assign) NSInteger role;

@property (nonatomic, strong) UISearchBar *searchBar;



@end

@implementation LCSearchVC
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self searchNavigationBar];

    
}

- (void)searchNavigationBar {
    
    self.customNavigation = [[UIView alloc]init];
    [self.view addSubview:self.customNavigation];
    

    CGFloat statusBarHeight = CGRectGetHeight([UIApplication sharedApplication].statusBarFrame);
    statusBarHeight += 44;
    CGFloat height  = (self.historys.count > 0) ? 44 : 0;
    statusBarHeight += height;
    
    [self.customNavigation mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.and.right.mas_equalTo(0);
        make.height.mas_equalTo(statusBarHeight);
    }];

    UIImageView *navigationBackground = [[UIImageView alloc]init];
    navigationBackground.userInteractionEnabled = YES;
    navigationBackground.image = [UIImage imageNamed:@"navBackground"];
    [self.customNavigation addSubview:navigationBackground];

    [navigationBackground mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.and.top.and.bottom.mas_equalTo(0);
    }];
    
    UIView *navigationView = [[UIView alloc]init];
    navigationView.backgroundColor = [UIColor clearColor];
    [self.customNavigation addSubview:navigationView];
    [navigationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(0);
        make.height.mas_equalTo(44);
        make.bottom.mas_equalTo(self.customNavigation.mas_bottom).offset(-height);
    }];
    
    [self.customNavigation bringSubviewToFront:navigationView];
    
    
    UIView *searchBaseView = [[UIView alloc]init];
    searchBaseView.backgroundColor = [UIColor whiteColor];
    searchBaseView.layer.cornerRadius = 4.0f;
    searchBaseView.layer.masksToBounds = YES;
    [navigationView addSubview:searchBaseView];

    [searchBaseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-50);
        make.centerY.mas_equalTo(navigationView.mas_centerY);
        make.bottom.mas_equalTo(-5);
        make.height.mas_equalTo(80);
    }];
//
//
    _searchBar = [[UISearchBar alloc]init];
    _searchBar.placeholder = @"搜索文件名";
    _searchBar.barStyle = UIBarStyleDefault;
    _searchBar.barTintColor = [UIColor whiteColor];
    _searchBar.searchBarStyle = UISearchBarStyleProminent;
    _searchBar.delegate = self;
    [searchBaseView addSubview:_searchBar];

    [_searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(searchBaseView);
    }];
    
    UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel setTitle:@"取消" forState:UIControlStateSelected];
    [cancel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancel setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [cancel addTarget:self action:@selector(dismissSearchVC) forControlEvents:UIControlEventTouchUpInside];
    [navigationView addSubview:cancel];
    
    [cancel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(searchBaseView.mas_centerY);
        make.right.mas_equalTo(-5);
    }];
    
    [self.collection mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(statusBarHeight - 44);
    }];
    
    [self.view insertSubview:self.customNavigation belowSubview:self.collection];



}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view becomeFirstResponder];
    self.collection.backgroundColor = [UIColor clearColor];

    self.role = 0;
    self.navigationController.delegate = self;
    if ([UserDefault objectForKey:@"searchHistory"]) {
        NSArray *historys = [UserDefault objectForKey:@"searchHistory"];
        self.historys = [NSMutableArray arrayWithArray:historys];
    }
    self.noDatasDes.hidden = (self.historys.count > 0);
    self.collection.hidden = !(self.historys.count > 0);


    
    self.fileType = @[@"全部",@"文档",@"图片",@"视频",@"音乐"];
    self.searchPage = 1;
//    [self.collection mas_updateConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(statusBarHeight);
//    }];
//
//        [self.view insertSubview:self.customNavigation belowSubview:self.collection];

    
    
//    LCSearchResultVC *result = [self.storyboard instantiateViewControllerWithIdentifier:@"LCSearchResultVC"];
//    self.results = [NSMutableArray arrayWithCapacity:0];
//
//    UISearchController *searchVC = [[UISearchController alloc]initWithSearchResultsController:result];
//    searchVC.searchResultsUpdater = self;
//    searchVC.dimsBackgroundDuringPresentation = NO;
//    searchVC.hidesNavigationBarDuringPresentation = NO;
//    searchVC.searchBar.showsCancelButton = NO;
//    searchVC.searchBar.barStyle = UIBarStyleDefault;
//
//    searchVC.searchBar.delegate = self;
//    [searchVC.searchBar becomeFirstResponder];
//    searchVC.searchBar.placeholder = @"搜索文件名";
//
//    [searchVC.searchBar setValue:@"取消" forKey:@"_cancelButtonText"];
//    searchVC.searchBar.tintColor = [UIColor whiteColor];
//    searchVC.searchBar.layer.backgroundColor = [UIColor clearColor].CGColor;
//
//    self.searchController = searchVC;
//    [self.customNavigation addSubview:searchVC.searchBar];

    
//    UITextField *textField = [searchVC.searchBar valueForKey:@"_searchField"];
//    [textField resignFirstResponder];
#warning 使用时遇到的问题
//    self.definesPresentationContext = YES;
    
    
//    UIView *customNavigation = [[UIView alloc]init];
//    customNavigation.backgroundColor = [UIColor redColor];
//    [self.view addSubview:customNavigation];
//
//    [customNavigation mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.and.top.and.right.mas_equalTo(0);
//        make.height.mas_equalTo(100);
//    }];
    
//    UIView *searchBarBaseView = [[UIView alloc]init];
//    [customNavigation addSubview:searchBarBaseView];
//
//    [searchBarBaseView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.and.right.and.bottom.mas_equalTo(0);
//        make.height.mas_equalTo(50);
//    }];
//
//    [searchBarBaseView addSubview:searchVC.searchBar];

    
    

}

- (void)dismissSearchVC {

    [self dismissViewControllerAnimated:YES completion:nil];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // 这里通过searchController的active属性来区分展示数据源是哪个
    if (self.searchController.active) {
        
        return self.results.count ;
    }
    
    return self.datas.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
    }
    
    // 这里通过searchController的active属性来区分展示数据源是哪个
    if (self.searchController.active ) {
        
        cell.textLabel.text = [self.results objectAtIndex:indexPath.row];
    } else {
        
        cell.textLabel.text = [self.datas objectAtIndex:indexPath.row];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.searchController.active) {
        NSLog(@"选择了搜索结果中的%@", [self.results objectAtIndex:indexPath.row]);
    } else {
        
        NSLog(@"选择了列表中的%@", [self.datas objectAtIndex:indexPath.row]);
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc]init];
    headerView.backgroundColor = [UIColor redColor];
//    self.tableView.tableHeaderView = headerView;
    return headerView;

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return _headHeight;
}



- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
    }
    
    return _tableView;
}

- (NSMutableArray *)datas {
    if (_datas == nil) {
        _datas = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _datas;
}

- (NSMutableArray *)results {
    if (_results == nil) {
        _results = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _results;
}



- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"点击取消按钮");
    
    [self dismissViewControllerAnimated:NO completion:^{
        
    }];

}

#pragma mark - UISearchResultsUpdating

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    if (self.searchController.active) {
        NSLog(@"激活 %@ ",searchController.searchBar.text);
        [self.results removeAllObjects];
        [self.historys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj rangeOfString:searchController.searchBar.text].location != NSNotFound) {
                [self.results addObject:obj];
            }
        }];
        
    }else{
        NSLog(@"未激活");
    }
    NSLog(@"results = %@",self.results);
    [self.collection reloadData];
}
#pragma mark - -

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        header.backgroundColor = [UIColor whiteColor];
        return header;
    }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
        
        WS(weakSelf);
        LCSearchHistoriesFooter *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
        footer.removeRecode = ^{
            [UserDefault setObject:nil forKey:@"searchHistory"];
            [UserDefault synchronize];
            [weakSelf.historys removeAllObjects];
            [weakSelf.collection reloadData];
        };
        return footer;
    }
    return nil;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
   
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;

    if (self.searchKey.length > 0) {
        //  开始搜索
        if (section == 0) {
            //  文件类型选择
            LCFileTypeCell *fileType = [collectionView dequeueReusableCellWithReuseIdentifier:@"fileType" forIndexPath:indexPath];
            if (self.fileType.count > row) {
                [fileType updateFileTypeCellWithParameter:self.fileType[row]];
            }
            return fileType;
        }else if (section == 1){
            //  文件列表
            LCFileCell *fileTypeCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"fileCell" forIndexPath:indexPath];
            NSInteger row = [indexPath row];
            if (self.results.count > row) {
                [fileTypeCell updateFileCellWithParameter:self.results[row]];

            }
            return fileTypeCell;

        }
    }else{
        //  历史记录
        LCSearchCell *searchCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"searchCell" forIndexPath:indexPath];
        searchCell.searchHistory.text = self.historys[indexPath.row];
        return searchCell;

    }
    return nil;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    NSInteger itemCount = 0;
    if (self.searchKey.length > 0) {
        if (section == 0) {
            //  文件类型
            itemCount = self.fileType.count;
        }else{
            itemCount = self.results.count;
        }
    }else{
        itemCount = (self.searchController.active) ? self.results.count : self.historys.count;

    }
    return itemCount;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    CGFloat height = 50;
    if (self.searchKey.length > 0) {
        height = 0;
    }

    return CGSizeMake(SWidth, height);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;

    CGFloat height = 0;
    CGFloat widht = 0;
    if (self.searchKey.length > 0) {
        if (section == 0) {
            widht = SWidth / (self.fileType.count);
            height = SWidth / (self.fileType.count);

        }else{
            widht = SWidth;
            height = 80;
        }
    }else{
        widht = SWidth;
        height = 50;

    }
    return CGSizeMake(widht, height);
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
   
    NSInteger sectionCount = 1;
    if (self.searchKey.length > 0) {
        sectionCount = 2;
    }
    return sectionCount;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    
    CGFloat footer = 50;
    if (self.searchKey.length > 0) {
        footer = 0;
    }
    return CGSizeMake(SWidth, footer);

}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    return YES;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;

    if (self.searchKey.length > 0) {
         //  搜索
        if (section == 0) {
             //  文件类型点击
            LCLog(@"文件类型点击");
            self.role = row;
            [self searchFileWithType:0];



        }else{
            //  点击搜索到的文件
            LCLog(@"点击搜索到的文件");
            self.actionBaseViewHeight.constant = 50;
            self.actionBaseView.hidden = NO;
        }
        
    }else{
        
        LCLog(@"点击搜索历史");
        NSArray *history = [UserDefault objectForKey:@"searchHistory"];
        NSString *searchKey = history[row];
        self.searchKey = searchKey;
        _searchBar.text = searchKey;
        [self searchFileWithType:0];

    
        
    }

}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    BOOL isTermService = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isTermService animated:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    self.searchKey = searchBar.text;
    if ([UserDefault objectForKey:@"searchHistory"]) {
        NSArray *historys = [UserDefault objectForKey:@"searchHistory"];
        NSMutableArray *temp = [NSMutableArray arrayWithArray:historys];
        if (![temp containsObject:searchBar.text]) {
            [temp addObject:searchBar.text];
        }
        [UserDefault setObject:temp forKey:@"searchHistory"];
        [UserDefault synchronize];
    }else{
        NSArray *history = @[searchBar.text];
        [UserDefault setObject:history forKey:@"searchHistory"];
        [UserDefault synchronize];
    }
    [self searchFileWithType:0];

}


- (void)searchFileWithType:(NSInteger)type {
    
    [self.view endEditing:YES];
    NSString *searchURL = [NSString stringWithFormat:@"/api/v0/nas/search?name=%@&role=%ld&page=%ld&pageSize=10",self.searchKey,(long)self.role,(long)self.searchPage];

    [[LCNetwork shareInstance]lc_getNetworkWithURL:searchURL responseSuccess:^(id resultCode, id resultParameter) {
        
        if ([resultCode isEqualToString:@"0"]) {
            NSDictionary *data = resultParameter[@"data"];
            NSArray *files = data[@"files"];
            LCLog(@"files = %@",files);
            
            if (files.count > 0) {
                
                [self.results addObjectsFromArray:files];
                [self.collection reloadData];
            }
        }
    } responseFail:^(id resultCode, NSError *error) {
        
    }];
}

- (IBAction)savaFile:(id)sender {
    
    [self showHint:@"保存到相册"];
}

- (IBAction)delFile:(id)sender {
    
    [self showHint:@"删除文件"];
}

- (IBAction)editFileTag:(id)sender {
    
    [self showHint:@"编辑标签"];
    
    [self performSegueWithIdentifier:@"serachFileEditTag" sender:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
